package com.wtao.testcamera;

import android.annotation.SuppressLint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.EditText;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

/**
 * SurfaceView也播不出来 rtsp摄像头的流数据
 */
public class RtspSurfacePlayActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    String TAG = "RtspActivity";
    private SurfaceView surfaceView;
    private EditText etUrl;
    private Boolean flag = true;
    String url = null;
    MediaPlayer mediaPlayer;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rtsp_camera);
        surfaceView = findViewById(R.id.surfaceView);
        etUrl = findViewById(R.id.etUrl);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnPreparedListener(preparedListener);
        mediaPlayer.setOnErrorListener(onErrorListener);
        /*findViewById(R.id.btnPlay).setOnClickListener(v->{
            Log.e(TAG, "点击了");
            if(etUrl.getText()!=null){
                url = etUrl.getText().toString();
                setOnlineAd();
            }
        });*/
        url = etUrl.getText().toString();
        setOnlineAd();
    }

    private void setOnlineAd(){
        if (url.startsWith("rtsp://")) {
            Log.e(TAG, "setOnlineAd()");
            //url是你要播放的视频
            surfaceView.getHolder().addCallback(this);
            surfaceView.getHolder().setFixedSize(1920,1080);
            try{
                mediaPlayer.setDataSource(url);
                Log.e(TAG, "设置源："+url);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
    private MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
            Log.e(TAG, "onPrepared");
        }
    };
    private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(TAG, "onError");
            return true;
        }
    };
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }
}